package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * This util class 
 * 
 * @author cuche
 * Class for nummeric name giving
 */
public class FileCounter {
	//static String for saving counter in a file, in case Server has a shutdown
	// counter.txt is found in "C:\eclipse"
	private static final String COUNTER_FILE = "counter.txt";
	private static FileCounter instance;
	private final AtomicInteger counter;
	
	
	/**
	 * 
	 * @return instance of counter
	 */
	public static FileCounter getInstance() {
		if (instance == null) {
			instance = new FileCounter();
		}
		return instance;
	}
	
	/**
	 * Private constructor for the Singleton pattern.
	 * Prevents construction of object more than one time.
	 * Only one instance of the Counter exists
	 */
	private FileCounter () {
		Integer counterFromFile = readCounterFromFile();
		if (counterFromFile != null) {
			counter = new AtomicInteger(counterFromFile);
		} else {
			counter = new AtomicInteger();
		}	
	}
	
	/**
	 * Method: getNextCounter
	 * 
	 * increments counter and uses writeCounterToFile to
	 * write the new counter in the file
	 * return: counterValue
	 */
	public int getNextCounter() {
		int counterValue = counter.incrementAndGet();
		writeCounterToFile(counterValue);
		return counterValue;
	}
	
	/**
	 * 
	 * @param counterValue
	 * 
	 * gets the counterValue and saves it in the COUNTER_FILE(counter.txt)
	 * with help of a BufferedWriter
	 */
	private void writeCounterToFile(int counterValue) {
		BufferedWriter writer = null;
		try {
			File counterFile = new File(COUNTER_FILE);
		    writer = new BufferedWriter(new FileWriter(counterFile));
		    writer.write(String.valueOf(counterValue));
		} catch (IOException e) {
			e.getLocalizedMessage();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.getLocalizedMessage();
			}
		}
	}
	

	/**
	 * This method reads the COUNTER_FILE(counter.txt) with help of a BufferedReader
	 * and returns the Value of the counter
	 * 
	 * @return counterFromFile
	 */
	private Integer readCounterFromFile() {
		Integer counterFromFile = null;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(COUNTER_FILE));
			String counterAsString = br.readLine();
			counterFromFile = Integer.valueOf(counterAsString);
			
		} catch (FileNotFoundException e) {
			e.getMessage();
		} catch (IOException e) {
			e.getMessage();
		} finally {
	        try {
				if (br != null) br.close();
			} catch (IOException e) {
				e.getMessage();
			}
	    }
		 return counterFromFile;
	}
}
